package com.linkage.usercenter.controller;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.StrUtil;
import com.github.pagehelper.PageInfo;
import com.linkage.common.base.RequestInfo;
import com.linkage.common.base.ResponseInfo;
import com.linkage.common.constant.CommonSysConstant;
import com.linkage.common.util.RedisUtils;
import com.linkage.usercenter.pojo.entity.CoreUser;
import com.linkage.usercenter.pojo.entity.MgrLoginDaily;
import com.linkage.usercenter.pojo.vo.*;
import com.linkage.usercenter.pojo.vo.managevo.MgDptInfosLineVO;
import com.linkage.usercenter.service.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/exter")
public class ManageController {

    private static final Logger logger = LoggerFactory.getLogger(ManageController.class);


    @Autowired
    private IManageService manageService;
    @Autowired
    private IuserToolService userToolService;

    @Autowired
    private IuserService userService;

    @Autowired
    private IDepService depService;

    @Autowired
    private MgrLoginService mgrLoginService;

    //查询部门简单信息  (入参getDptInfos)
    @RequestMapping(value = "/manage/getDptInfos", method = RequestMethod.POST)
    public String getDptInfos(@RequestBody RequestInfo<Map<String, String>> query){
        String orgCode = query.getBuss().get("paramVar");
        List<DptInfoVO> list =  manageService.getDptInfos(orgCode);
        return ResponseInfo.success(list).toString();
    }

    //查询部门信息  (  1保安 2警察 6自招  9 所有)
    @RequestMapping(value = "/manage/getDptList", method = RequestMethod.POST)
    public String getDptList(@RequestBody RequestInfo<Map<String, String>> query){
        String orgCode = query.getBuss().get("paramVar");
        if(StrUtil.isBlank(orgCode)){
            return ResponseInfo.error("入参不能为空！").toString();
        }
        List<DptInfoLevelVO> list =  manageService.getDptList(orgCode);
        return ResponseInfo.success(list).toString();
    }

    //查询部门信息  (  1保安 2警察  9 所有)
    @RequestMapping(value = "/manage/getDptListWithUser", method = RequestMethod.POST)
    public String getDptListWithUser(@RequestBody RequestInfo<Map<String, String>> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        String orgCode = query.getBuss().get("paramVar");
        if(StrUtil.isBlank(orgCode)){
            return ResponseInfo.error("入参不能为空！").toString();
        }
        List<DptUserVo> list =  manageService.getDptListWithUser(orgCode,userInfoToken);
        return ResponseInfo.success(list).toString();
    }



    //查询权限分组（角色）信息（0 停用   1 正常 9 所有）
    @RequestMapping(value = "/manage/getRoleOperateInfo", method = RequestMethod.POST)
    public String getRoleOperateInfo(@RequestBody RequestInfo<Map<String, String>> query){
        String roleType = query.getBuss().get("paramVar");
        if(StrUtil.isBlank(roleType)){
            return ResponseInfo.error("入参不能为空！").toString();
        }
        List<MgRoleVO> list =  manageService.getRoleOperateInfo(roleType);
        return ResponseInfo.success(list).toString();
    }


    //修改人员权限分组或机构信息
//    @RequestMapping(value = "/manage/changeUserROInfo", method = RequestMethod.POST)
//    public String changeUserROInfo(@RequestBody RequestInfo<UserMgInfoQUERY> query){
//        UserMgInfoQUERY requestInfo = query.getBuss();
//        if(requestInfo == null){
//            return ResponseInfo.error("入参不能为空！").toString();
//        }
//        manageService.changeUserROInfo(requestInfo);
//        return ResponseInfo.success().toString();
//    }

    //根据手机号 身份证 或用户编码查询人员信息
    @RequestMapping(value = "/manage/getUserMgInfoVO", method = RequestMethod.POST)
    public String getUserMgInfoVO(@RequestBody RequestInfo<Map<String, String>> query){
        String param = query.getBuss().get("paramVar");
        if(StrUtil.isBlank(param)){
            return ResponseInfo.error("入参不能为空！").toString();
        }
        UserMgInfoVO  userMgInfoVO =  manageService.getUserMgInfoVO(param);
        return ResponseInfo.success(userMgInfoVO).toString();
    }

    //根据手机号 或 用户姓名查询被审核人员信息 包含审核列表
    // paramVar  手机号或  姓名
    // flag  0为手机号
    // checkFlag   （0：正常-审核通过；1：离职-审核拒绝,2：初始化  空 所有）人员类型
    // personClass (0群众 1保安 2警察,3超级管理员 4. 一级管理员  5.二级管理员 6 自建人员 9 运营商)
    @RequestMapping(value = "/manage/getAuditEmpList", method = RequestMethod.POST)
    public String getAuditEmpList(@RequestBody RequestInfo<Map<String, String>> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        String flag = query.getBuss().get("flag");
        // （0：正常-审核通过；1：离职-审核拒绝,2：初始化  空 所有）
        String checkFlag = query.getBuss().get("checkFlag");
        String personClass = query.getBuss().get("personClass");
        String param = query.getBuss().get("paramVar");
        if(StrUtil.isBlank(personClass)){
            return ResponseInfo.error("入参personClass不能为空！").toString();
        }
        List<UserMgInfoVO>  list =  manageService.getAuditEmpList(param,userInfoToken,checkFlag, personClass);
        return ResponseInfo.success(list).toString();
    }

    //根据手机号 身份证 或用户编码或用户编码 用户姓名查询人员信息
    @RequestMapping(value = "/manage/getUserMgInfoVOList", method = RequestMethod.POST)
    public String getUserMgInfoVOList(@RequestBody RequestInfo<Map<String, String>> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        String param = query.getBuss().get("paramVar");
        if(StrUtil.isBlank(param)){
            return ResponseInfo.error("入参不能为空！").toString();
        }
        List<UserMgInfoVO>  list =  manageService.getUserMgInfoVOList(param, userInfoToken);
        return ResponseInfo.success(list).toString();
    }

    //根据用户id查询所属上级部门管理员
    @RequestMapping(value = "/manage/getSuperiorManager", method = RequestMethod.POST)
    public String getSuperiorManager(@RequestBody RequestInfo<Map<String, String>> query){
        String param = query.getBuss().get("userCode");
        if(StrUtil.isBlank(param)){
            return ResponseInfo.error("入参不能为空！").toString();
        }
        UserMgInfoVO userInfo = manageService.getSuperiorManager(param);
        if(userInfo == null){
            return ResponseInfo.error("管理员信息为空").toString();
        }
        return ResponseInfo.success(userInfo).toString();
    }



    //权限分组  查询后台所有权限信息   权限状态 6验收数据  1 正常数据  0停用数据 默认6
    @RequestMapping(value = "/manage/queryAllOperatorInfos", method = RequestMethod.POST)
    public String queryAllOperatorInfos(@RequestBody RequestInfo<Map<String, String>> query){
        String param = query.getBuss().get("paramVar");
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        List<CodeOperateVO> list = manageService.queryAllOperatorInfos(param,userInfoToken);
        return ResponseInfo.success(list).toString();
    }

    //权限分组 添加修改权限分组
    @RequestMapping(value = "/manage/setOperatorGrop", method = RequestMethod.POST)
    public String setOperatorGrop(@RequestBody RequestInfo<MgRoleQUERY> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        MgRoleQUERY requestInfo = query.getBuss();
        manageService.setOperatorGrop(requestInfo, userInfoToken);
        return ResponseInfo.success().toString();
    }

    //权限分组 查看权限分组
    @RequestMapping(value = "/manage/catOperatorGrop", method = RequestMethod.POST)
    public String catOperatorGrop(@RequestBody RequestInfo<Map<String, String>> query){
        String param = query.getBuss().get("paramVar");
        MgInfoVO vo = manageService.catOperatorGrop(param);
        return ResponseInfo.success(vo).toString();
    }
    //权限分组 删除权限分组
    @RequestMapping(value = "/manage/delOperatorGrop", method = RequestMethod.POST)
    public String delOperatorGrop(@RequestBody RequestInfo<Map<String, List<String>>> query){
        List<String> roleCodeList  = query.getBuss().get("paramVar");
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        manageService.delOperatorGrop(roleCodeList, userInfoToken);
        return ResponseInfo.success().toString();
    }
    //权限分组 查询本人的权限分组列表
    @RequestMapping(value = "/manage/queryOwerOperatorGrop", method = RequestMethod.POST)
    public String queryOwerOperatorGrop(@RequestBody  RequestInfo<Map<String, String>> query){
        String param = query.getBuss().get("paramVar");
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        List<MgRoleVO> list = manageService.queryOwerOperatorGrop(userInfoToken);
        return ResponseInfo.success(list).toString();
    }

    //部门管理  根据部门代码查询部门所有人员信息
    @RequestMapping(value = "/manage/getDptUserInfo", method = RequestMethod.POST)
    public String getDptUserInfo(@RequestBody RequestInfo<Map<String, String>> query){
        String dptCode = query.getBuss().get("paramVar");
        if(StrUtil.isBlank(dptCode)){
            return ResponseInfo.error("入参不能为空！").toString();
        }
        List<UserMgInfoVO> list =  manageService.getDptUserInfo(dptCode);
        return ResponseInfo.success(list).toString();
    }

    //部门管理   所有人员(警察和保安)信息
    @RequestMapping(value = "/manage/getLocationUsers", method = RequestMethod.POST)
    public String getLocationUsers(@RequestBody RequestInfo<Map<String, String>> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        if(query.getBuss().containsKey("userName")){
            userInfoToken.setUserRealName(query.getBuss().get("userName"));
        }else{
            userInfoToken.setUserRealName(null);
        }
        List<UserMgInfoVO> list =  manageService.getLocationUsers(userInfoToken);
        return ResponseInfo.success(list).toString();
    }

    //部门管理  删除用户数据
    @RequestMapping(value = "/manage/delUserByUsercode", method = RequestMethod.POST)
    public String delUserByUsercode(@RequestBody RequestInfo<Map<String, String>> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        String param = query.getBuss().get("paramVar");
        manageService.delUserByUsercode(param, userInfoToken);
        return ResponseInfo.success().toString();
    }

    //部门管理 新增或修改人员
    @RequestMapping(value = "/manage/changeUserDptInfo", method = RequestMethod.POST)
    public String changeUserDptInfo(@RequestBody RequestInfo<UserMgInfoQUERY> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        UserMgInfoQUERY requestInfo = query.getBuss();
        if(requestInfo == null){
            return ResponseInfo.error("入参不能为空").toString();
        }
        manageService.changeUserROInfo(requestInfo, userInfoToken);
        return ResponseInfo.success().toString();
    }
    //部门管理   查询个人下属部门信息
    @RequestMapping(value = "/manage/getOwerDptList", method = RequestMethod.POST)
    public String getOwerDptList(@RequestBody RequestInfo<Map<String, String>> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        //预留，是否 上级  本级 下级 或其它组合
        String paramVar = query.getBuss().get("paramVar");
        List<DptInfoLevelVO> list =  manageService.getOwerDptList(paramVar, userInfoToken);
        return ResponseInfo.success(list).toString();
    }


    //权限设置  查询个人创建的二级管理员列表
    @RequestMapping(value = "/manage/getOwerUserInfo", method = RequestMethod.POST)
    public String getOwerUserInfo(@RequestBody RequestInfo<Map<String, String>> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        //预留，如查询删除或停用账号信息
        String userType = query.getBuss().get("paramVar");
        List<UserMgInfoVO> list =  manageService.getOwerUserInfo(userType, userInfoToken);
        return ResponseInfo.success(list).toString();
    }

    //权限设置 删除二级管理员
    @RequestMapping(value = "/manage/delUserOprInfo", method = RequestMethod.POST)
    public String delUserOprInfo(@RequestBody RequestInfo<UserMgDeleteQUERY> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        UserMgDeleteQUERY requestInfo = query.getBuss();
        manageService.delUserOprInfo(requestInfo, userInfoToken);
        return ResponseInfo.success().toString();
    }

    //权限设置 新增或编辑二级管理员
    @RequestMapping(value = "/manage/addUserOprInfo", method = RequestMethod.POST)
    public String addUserOprInfo(@RequestBody RequestInfo<UserMgAddQUERY> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        UserMgAddQUERY requestInfo = query.getBuss();
        manageService.addUserOprInfo(requestInfo, userInfoToken);
        return ResponseInfo.success().toString();
    }

    //修改其他人员密码
    @RequestMapping(value = "/manage/changePasswordByUserCode", method = RequestMethod.POST)
    public String changePasswordByUserCode(@RequestBody RequestInfo<MgPasswordQUERY> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        MgPasswordQUERY requestInfo = query.getBuss();
        manageService.changePasswordByUserCode(requestInfo, userInfoToken);
        return ResponseInfo.success().toString();
    }

    //管理后台 用户登录  用户名 密码
    @RequestMapping(value = "/manage/login", method = RequestMethod.POST)
    public String login(@RequestBody RequestInfo<ExterLoginQUERY> query) {
        ExterLoginVO vo = new  ExterLoginVO();
        vo.setFrom("1");
        userService.login(query, vo);
        return ResponseInfo.success(vo).toString();
    }

    //调度台设置， 机构警务在线查询 超级管理员
    @RequestMapping(value = "/manage/queryDptsLine", method = RequestMethod.POST)
    public String queryDptsLine(@RequestBody RequestInfo<Map<String, String>> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
//        String orgType = query.getBuss().get("paramVar");
        MgDptInfosLineVO vo = new  MgDptInfosLineVO();
        userService.queryDptsLine(query, vo);
        return ResponseInfo.success(vo).toString();
    }

    //调度台设置， 手机号校验
    @RequestMapping(value = "/manage/checkMobile", method = RequestMethod.POST)
    public String checkMobile(@RequestBody RequestInfo<Map<String, String>> query){
        String bolile = query.getBuss().get("paramVar");
        userService.checkMobile(bolile);
        return ResponseInfo.success().toString();
    }

    //20210110新增需求 手机运营商更新
    @RequestMapping(value = "/manage/updatePhoneFlag", method = RequestMethod.POST)
    public String updatePhoneFlag(@RequestBody RequestInfo<Map<String, String>> query){
        String mobiles = query.getBuss().get("paramVar");
        manageService.updatePhoneFlag(mobiles);
        return ResponseInfo.success().toString();
    }

    //调度台设置， 管理员账号校验
    @RequestMapping(value = "/manage/checkUserCode", method = RequestMethod.POST)
    public String checkUserCode(@RequestBody RequestInfo<Map<String, String>> query){
        String userCode = query.getBuss().get("paramVar");
        userService.checkUserCode(userCode);
        return ResponseInfo.success().toString();
    }

    //调度台设置， 后台添加保安信息
    @RequestMapping(value = "/manage/addUserForSecurity", method = RequestMethod.POST)
    public String addUserForSecurity(@RequestBody RequestInfo<MgUserSecurityQUERY> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        userService.addUserForSecurity(query, userInfoToken);
        //更新保安手机归属信息
        manageService.mobileTransfer(Arrays.asList(query.getBuss().getUserMobile()));
        return ResponseInfo.success().toString();
    }
    //调度台设置， 新增部门/企业信息一级管理员信息
    @RequestMapping(value = "/manage/addManageLevelOne", method = RequestMethod.POST)
    public String addManageLevelOne(@RequestBody RequestInfo<MgUserManageQUERY> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        userService.addManageLevelOne(query, userInfoToken);
        return ResponseInfo.success().toString();
    }
    //调度台设置， 修改部门/企业信息一级管理员信息
    @RequestMapping(value = "/manage/updateManageLevelOne", method = RequestMethod.POST)
    public String updateManageLevelOne(@RequestBody RequestInfo<MgUserManageQUERY> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        query.getBuss().setUpdateFlag("1");
        userService.addManageLevelOne(query, userInfoToken);
        return ResponseInfo.success().toString();
    }
    //调度台设置， 删除部门/企业信息一级管理员信息
    @RequestMapping(value = "/manage/deleteManageLevelOne", method = RequestMethod.POST)
    public String deleteManageLevelOne(@RequestBody RequestInfo<MgUserManageQUERY> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        query.getBuss().setUpdateFlag("2");
        userService.addManageLevelOne(query, userInfoToken);
        return ResponseInfo.success().toString();
    }
    //调度台设置， 查询部门/企业信息一级管理员信息
    @RequestMapping(value = "/manage/queryManageLevelOne", method = RequestMethod.POST)
    public String queryManageLevelOne(@RequestBody RequestInfo<MgUserManageQUERY> query){
        CoreUser userInfoToken = userToolService.getUserInfoByToken(query);
        MgUserManageQUERY vo = userService.queryManageLevelOne(query, userInfoToken);
        return ResponseInfo.success(vo).toString();
    }

    //调度台设置， 查询归属上级 归属总公司 1 警务部门  0 企业
    @RequestMapping(value = "/manage/queryManageParentDpt", method = RequestMethod.POST)
    public String queryManageParentDpt(@RequestBody RequestInfo<Map<String, String>> query){
        String dptType = query.getBuss().get("paramVar");
        List<DptParentVO> dptList = userService.queryManageParentDpt(dptType);
        return ResponseInfo.success(dptList).toString();
    }

    /**
     * 根据类型查询审核信息-警务
     * @param query  status：0-未处理，1-已通过，2-已拒绝 type：0-警务，1-企业
     * @return
     */
    @RequestMapping(value = "/manage/queryAuditList",method = RequestMethod.POST)
    public String queryAuditList(@RequestBody RequestInfo<Map<String, String>> query){
        //TODO 校验登录用户是否具有运营商或管理权限
        String personClass = query.getBase().getUsertoken().split(":")[2];
        logger.info("访问用户personClass为："+personClass);
        if(!StrUtil.equals(CommonSysConstant.PERSON_YY_FLAG,personClass) ){
            if(!StrUtil.equals(CommonSysConstant.PERSON_CJGLYFLAG,personClass)){
                return ResponseInfo.error("当前用户不具备运营商权限").toString();
            }
        }
        String status = query.getBuss().get("status");
        List list = depService.queryAuditList(status);
        return ResponseInfo.success(list).toString();
    }

    /**
     * 根据类型查询审核信息-警务
     * @param query  status：0-通过，1-拒绝 type：0-警务，1-企业 code：企业dptCode或者保安userCode
     * @return
     */
    @PostMapping(value = "/manage/audit")
    public String audit(@RequestBody RequestInfo<Map<String, String>> query){
        String personClass = query.getBase().getUsertoken().split(":")[2];
        logger.info("访问用户personClass为："+personClass);
        if(!StrUtil.equals(CommonSysConstant.PERSON_YY_FLAG,personClass) ){
            if(!StrUtil.equals(CommonSysConstant.PERSON_CJGLYFLAG,personClass)){
                return ResponseInfo.error("当前用户不具备运营商权限").toString();
            }
        }
//        String type = query.getBuss().get("type");
        String status = query.getBuss().get("status");
        String code = query.getBuss().get("code");
        String expireTime = query.getBuss().get("expireTime");
        depService.audit(status,code,expireTime);
        return ResponseInfo.success().toString();
    }

    /**
     * 根据类型查询审核信息-警务
     * @param query  status：0-通过，1-拒绝 type：0-警务，1-企业 code：企业dptCode或者保安userCode
     * @return
     */
    @RequestMapping(value = "/manage/auditInfo",method = RequestMethod.POST)
    public String auditInfo(@RequestBody RequestInfo<Map<String, String>> query){
        String personClass = query.getBase().getUsertoken().split(":")[2];
        logger.info("访问用户personClass为："+personClass);
        if(!StrUtil.equals(CommonSysConstant.PERSON_YY_FLAG,personClass) ){
            if(!StrUtil.equals(CommonSysConstant.PERSON_CJGLYFLAG,personClass)){
                return ResponseInfo.error("当前用户不具备运营商权限").toString();
            }
        }
        String code = query.getBuss().get("code");
        Object obj = depService.auditInfo(code);
        return ResponseInfo.success(obj).toString();
    }

    /**
     * 保安，群众统计
     * @return
     */
    @PostMapping(value = "/manage/statisticsBA")
    public String statisticsBA(@RequestBody RequestInfo requestInfo){
        String token = requestInfo.getBase().getUsertoken();
        if(StrUtil.isEmpty(token)){
            return ResponseInfo.error("token 参数为空！").toString();
        }
        Map result = userService.statisticsBA(token);
        return ResponseInfo.success(result).toString();
    }

    @PostMapping(value="/manage/statisticsJC")
    public String statisticsJC(@RequestBody RequestInfo<Map<String,String>> mapRequestInfo){
        String deptCode = mapRequestInfo.getBuss().get("deptCode");
        String token = mapRequestInfo.getBase().getUsertoken();
        Map result = userService.statisticsJC(deptCode,token);
        return ResponseInfo.success(result).toString();
    }

    @PostMapping(value = "/manage/statisticsMgrLogin")
    public String statisticsMgrLogin(@RequestBody RequestInfo requestInfo){
        String token = requestInfo.getBase().getUsertoken();
        if(StrUtil.isEmpty(token)){
            return ResponseInfo.error("token 参数为空！").toString();
        }
        List<MgrLoginDaily> result = mgrLoginService.queryMgrLoginDailyTotal(token);
        return ResponseInfo.success(result).toString();
    }


    /*  *    小程序后台 - 获取用户信息列表  */
    @RequestMapping(value = "/manage/getUserInfoList", method = RequestMethod.POST)
    public String getUserInfoList(@RequestBody RequestInfo<UserInfoListQUERY> query) {
        PageInfo<UserInfoListVO> pageInfo =  userService.getUserInfoList(query);
        return ResponseInfo.successWithPage(pageInfo).toString();
    }


    /* * 修改用户信息 */
    @RequestMapping(value = "/manage/updatePersonInfo", method = RequestMethod.POST)
    public String updatePersonInfo(@RequestBody RequestInfo<UpdateUserQUERY> query) {
        userService.updatePersonInfo(query);
        return ResponseInfo.success().toString();
    }

    /**
     * 查询部门下的一二级管理员
     * @param requestInfo
     * @return
     */
    @PostMapping("/manage/queryMgInfoByDptCode")
    public String queryMgInfoByDptCode(@RequestBody RequestInfo<Map<String, String>> requestInfo){
        if(!requestInfo.getBuss().containsKey("dptCode")){
            throw new ValidateException(500,"部门Code为空");
        }
        List<UserMgInfoVO> list = manageService.queryMgListByDptCode(requestInfo.getBuss().get("dptCode"));
        return ResponseInfo.success(list).toString();
    }


    //退出登录
    @RequestMapping(value = "/manage/loginOut", method = RequestMethod.POST)
    public String loginOut(@RequestBody RequestInfo requestInfo){
        String token = requestInfo.getBase().getUsertoken();
        if(StrUtil.isEmpty(token)){
            return ResponseInfo.error("token 参数为空！").toString();
        }
        userService.loginOut(token);
        return ResponseInfo.success().toString();
    }

}
